import {
  login,
  logout,
  getUserInfo,
  refreshToken
} from '@/api/user'

import Util from '@/utils'
import Storage from '@/utils/storage'

export default {
  state: {
    uid: '',
    name: '',
    avatar: '',
    token: Util.getToken(),
    status: ''
  },
  mutations: {
    setUserId(state, id) {
      state.uid = id
    },
    setUserName(state, name) {
      state.name = name
    },
    setAvator(state, avatar) {
      state.avatar = avatar
    },
    setStatus(state, status) {
      state.status = status
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
  },
  actions: {
    // 登录
    handleLogin({
      commit,
    }, data) {
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          const data = res.data
          commit('setToken', data.access_token)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut({
      commit
    }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('setToken', '')
          Util.removeToken()
          Storage.clearAll()
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取用户相关信息
    getUserInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo().then(res => {
            const data = res.data
            commit('setUserId', data.id)
            commit('setUserName', data.name)
            commit('setAvator', data.avator)
            commit('setStatus', data.status)
            Storage.set('user', data)
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    refreshToken({
      commit
    }) {
      return new Promise((resolve, reject) => {
        try {
          refreshToken().then(res => {
            const data = res.data
            commit('setToken', data.access_token)
            resolve(res)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
